"""
数据库连接模块
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import QueuePool
from app.core.config import DevelopmentConfig
from contextlib import contextmanager
from app.utils.log_control import INFO, ERROR
import pymysql

# 注册 PyMySQL 作为 MySQLdb
pymysql.install_as_MySQLdb()

class DatabasePool:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialize()
        return cls._instance
    
    def _initialize(self):
        try:
            # 使用开发环境配置
            config = DevelopmentConfig()
            connection_url = f'mysql+pymysql://{config.MYSQL_USER}:{config.MYSQL_PASSWORD}@{config.MYSQL_HOST}:{config.MYSQL_PORT}/{config.MYSQL_DB}'
            
            self.engine = create_engine(
                connection_url,
                poolclass=QueuePool,
                pool_size=5,  # 连接池大小
                pool_recycle=3600,  # 连接回收时间
                pool_pre_ping=True  # 添加连接检查
            )
            self.Session = sessionmaker(bind=self.engine)
            INFO.logger.info("数据库连接池初始化成功")
        except Exception as e:
            ERROR.logger.error(f"数据库连接池初始化失败: {str(e)}")
            raise
    
    @contextmanager
    def get_connection(self):
        session = self.Session()
        try:
            yield session
            session.commit()
        except Exception as e:
            session.rollback()
            ERROR.logger.error(f"数据库操作失败: {str(e)}")
            raise
        finally:
            session.close()

# 创建全局数据库连接池实例
db_pool = DatabasePool() 